package org.jpro.modules.system.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.jpro.modules.system.dao.PermissionRepository;
import org.jpro.modules.system.entity.Permission;
import org.jpro.modules.system.service.IPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <P>功能描述 : 权限service实现 </P>
 * <P>File name : PermissionServiceImpl </P>
 * <P>Author : 王泽浩 </P>
 * <P>E-Mail : 1028625100@qq.com </P>
 * <P>Date : 2017/3/4 上午12:00</P>
 */
@Service
@Transactional(readOnly = true)
public class PermissionServiceImpl implements IPermissionService {

    @Autowired
    private PermissionRepository permissionRepository;

    @Override
    public List<Permission> getMenus() {
        return permissionRepository.findMenus();
    }

    @Override
    public List<Permission> getAll() {
        return permissionRepository.findAll();
    }

    @Override
    public List<Permission> getMenuOperation(Integer pid) {
        return permissionRepository.findMenuOperation(pid);
    }

    @Override
    public List<Permission> getPermissions(Integer userId) {
        return permissionRepository.findPermissions(userId);
    }

    @Override
    @Transactional
    public void save(Permission permission) {
        permissionRepository.save(permission);
    }

    @Override
    @Transactional
    public void addBaseOpe(Integer pid, String pClassName) {
        List<Permission> pList = new ArrayList<Permission>();
        pList.add(new Permission(pid, "添加", "O", "", "sys:" + pClassName + ":add"));
        pList.add(new Permission(pid, "删除", "O", "", "sys:" + pClassName + ":delete"));
        pList.add(new Permission(pid, "修改", "O", "", "sys:" + pClassName + ":update"));
        pList.add(new Permission(pid, "查看", "O", "", "sys:" + pClassName + ":view"));

        // 添加没有的基本操作
        List<Permission> existPList = getMenuOperation(pid);
        for (Permission permission : pList) {
            boolean exist = false;
            for (Permission existPermission : existPList) {
                if (permission.getPermCode().equals(existPermission.getPermCode())) {
                    exist = true;
                    break;
                } else {
                    exist = false;
                }
            }
            if (!exist) {
                save(permission);
            }
        }
    }

    @Override
    public Permission get(Integer id) {
        return permissionRepository.getOne(id);
    }

    @Override
    @Transactional(readOnly = false)
    public void delete(Integer id) {
        permissionRepository.delete(id);
    }
}
